import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client'
import { setContext } from '@apollo/client/link/context'
import { onError } from '@apollo/client/link/error'
import { getToken } from '@/utils'
import { history } from './history'
const cache = new InMemoryCache()
const isDev = (process.env.NODE_ENV === 'development')
const httpLink = createHttpLink({
  uri: isDev ? 'http://192.168.0.102:5001/' : `${origin}/reservation/`
})
const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = getToken()
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
})
const resetToken = onError(({ graphQLErrors, networkError, operation, forward }) => {
  if (graphQLErrors) {
    for (let err of graphQLErrors) {
      if (err.extensions.code === "UNAUTHENTICATED") {
        history.push('/login')
      }
    }
  }
})
const client = new ApolloClient({
  // Provide required constructor fields
  cache: cache,
  link: resetToken.concat(authLink).concat(httpLink),
  // Provide some optional constructor fields
  name: 'react-web-client',
  version: '1.3',
  queryDeduplication: false,
  defaultOptions: {
    watchQuery: {
      fetchPolicy: 'cache-and-network',
    },
  },
})
export { client }